﻿using DocumentFormat.OpenXml.Lite.Shared;
using DocumentFormat.OpenXml.Lite.Xml;
using DocumentFormat.OpenXml.Lite.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Schema;
using System.Xml.Serialization;
using DocumentFormat.OpenXml.Lite.Core;

namespace DocumentFormat.OpenXml.Lite.WordprocessingML.Word.Table.CellProperties
{
    /// <summary>
    /// Revision Information for Table Cell Properties
    /// </summary>
    [XmlRoot("tcPrChange", Namespace = Constants.WordMain)]
    public class PropertyChange : XmlSerializable, ITableCellPropElement
    {
        [XmlAttribute("id", Namespace = Constants.WordMain, Form = XmlSchemaForm.Qualified)]
        public int Id { get; set; }

        [XmlAttribute("author", Namespace = Constants.WordMain, Form = XmlSchemaForm.Qualified)]
        public string Author { get; set; }

        [XmlAttribute("date", Namespace = Constants.WordMain, Form = XmlSchemaForm.Qualified)]
        public DateTime Date { get; set; }

        [XmlElement("tcPr", Namespace = Constants.WordMain)]
        public XmlList<ITableCellPropElement> Properties { get; set; }

        public PropertyChange()
        {
            Properties = new XmlList<ITableCellPropElement>();
            Properties.Changing += Properties_Changing;
        }

        void Properties_Changing(object sender, ListEventArgs<ITableCellPropElement> args)
        {
            if (args.Type == ListEventType.Remove)
                return;

            foreach (var obj in args.Objects)
            {
                if (obj.GetType().IsInheritedFrom(typeof(ITableCellPropElement)))
                {
                    var element = Properties.FirstOrDefault(e => e.GetType() == obj.GetType());
                    if (obj != null)
                    {
                        throw new OpenXmlException("Element with the same type (" +
                            element.GetType().ToString() + ") already added to list: " + Properties.ToString());
                    }
                }
            }
        }

        public void Copy(object obj)
        {
            if (obj is PropertyChange)
            {
                this.Id = (obj as PropertyChange).Id;
                this.Date = (obj as PropertyChange).Date;
                this.Author = (obj as PropertyChange).Author;
                this.Properties = (obj as PropertyChange).Properties;
            }
        }
    }
}
